
const axios = require("axios");
const webhookUrl = process.env.NOTIFICATION_WEBHOOK;
const logger = require("./logger");
const collectBaseUrl = process.env.COLLECT_API_BASE_URL;
const collectAuthId = process.env.COLLECT_API_X_AUTH_ID;
const collectAuthToken = process.env.COLLECT_API_X_AUTH_TOKEN;
const dayjs = require("dayjs");
const customParseFormat = require("dayjs/plugin/customParseFormat");

dayjs.extend(customParseFormat);
//提取背景图片的URL
const extractImageUrl = (backgroundImageStyle) => {
  if (!backgroundImageStyle) return "";

  // 使用正则表达式匹配URL
  const match = backgroundImageStyle.match(/url\(['"]?(.*?)['"]?\)/);

  // 如果匹配成功，返回第一个捕获组（即URL），否则返回空字符串
  return match ? match[1] : "";
};
//微信webhook通知机器人
const sendWechatMessage = async (data) => {
  try {
    const res = await axios.post(webhookUrl, data);
    if (res.data.errcode === 0) {
      return res;
    } else {
      throw new Error(res.data.errmsg);
    }
  } catch (error) {
    throw error;
  }
};

//发布作品回调通知
async function publishCallback(id, status, message, task_id, platform_key) {
  logger.info(
    `回调参数:url: ${process.env.WF221_API_BASE_URL}"/auth/api/post/callback",id: ${id}, status: ${status}, message: ${message}, task_id: ${task_id}, platform_key（作品id）: ${platform_key}`
  );
  return await axios.put(
    process.env.WF221_API_BASE_URL + "/auth/api/post/callback",
    {
      id,
      status,
      message,
      task_id,
      platform_key,
    },
    {
      headers: {
        "X-AUTH": "5f228e09-bab0-4d6a-9d23-aed5c2d1db0d",
      },
    }
  );
}

// 抓取数据存储持久库方法
async function saveData(data) {
  const config = {
    method: "post",
    url: `${collectBaseUrl}/collect/api/single`,
    headers: {
      "X-Auth-Id": collectAuthId,
      "X-Auth-Token": collectAuthToken,
    },
    data: data,
  };
  try {
    const res = await axios(config);
    logger.info(`抓取数据存储持久库成功: ${JSON.stringify(res.data)}`);
    return res.data;
  } catch (error) {
    logger.error(`抓取数据存储持久库失败: ${error.message}`);
    if (error.response) {
      logger.error(`错误响应数据: ${JSON.stringify(error.response.data)}`);
    }
    throw error;
  }
}
// 日期格式处理
/***
 *
 * function: 解析日期字符串并格式化
 * params:
 * dateStr: 日期字符串
 * 格式：YYYY年M月D日早上HH点mm分 | YYYY年M月D日中午HH点mm分 | YYYY年M月D日下午HH点mm分 | YYYY年M月D日晚上HH点mm分 | YYYY年M月D日凌晨HH点mm分
 *
 * return:
 * 格式：YYYY-MM-DD HH:mm:ss
 *
 */
function convertToStandardFormat(dateStr) {
  const formatRegexMap = [
    {
      regex:
        /(\d{4})年(\d{1,2})月(\d{1,2})日(早上|上午|中午|下午|晚上|凌晨)(\d{1,2})点(?:(\d{1,2})分)?/,
      format: "YYYY年M月D日A HH点mm分",
    },
  ];

  for (const { regex, format } of formatRegexMap) {
    const match = dateStr.match(regex);
    if (match) {
      const [, year, month, day, period, hour, minute = "0"] = match;
      let parsedDate = dayjs(
        `${year}-${month}-${day} ${hour}:${minute}`,
        "YYYY-M-D H:m"
      );

      if ((period === "下午" || period === "晚上") && parsedDate.hour() < 12) {
        parsedDate = parsedDate.add(12, "hour");
      } else if (period === "凌晨" && parsedDate.hour() === 12) {
        parsedDate = parsedDate.subtract(12, "hour");
      }

      return parsedDate.isValid()
        ? parsedDate.format("YYYY-MM-DD HH:mm:ss")
        : "无效日期：日期解析成功但结果无效";
    }
  }

  return "无效日期：未匹配到任何支持的格式";
}

module.exports = {
  extractImageUrl,
  sendWechatMessage,
  publishCallback,
  saveData,
  convertToStandardFormat,
};
